import json
import datetime

from django.shortcuts import render, render_to_response
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.views.generic.base import View
from django.contrib.auth.hashers import make_password
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required


from users.models import UserProfile, EmailVerifyRecord
from users.forms import LoginForm, RegisterForm, ForgetForm, ModifyPwdForm, UploadImageForm
from util.email import send_register_email


# Create your views here.
# 404/403等处理
def page_not_found(request):
    return render_to_response('404.html')


# 返回到主页
# @login_required
def index(request):
    # user = request.user
    return render(request, 'index.html')


# 返回错误信息
def get_error(request):
    error = request["error"]
    return JsonResponse({"error": error})


# 自定义的一个用户验证过程，主要是返回该用户
class CustomBackend(ModelBackend):
    def authenticate(self, request, email_mobile=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(mobile=email_mobile) | Q(email=email_mobile))
            if user.check_password(password):
                return user
        except Exception as e:
            return e


# 激活用户的类
class ActiveUserView(View):
    @staticmethod
    def get(request, active_code):
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:
            for record in all_records:
                email = record.email
                user = UserProfile.objects.get(email=email)
                user.is_active = True
                user.save()
        else:
            pass
        return render(request, "users/login.html")


# 用户登录的类
class LoginView(View):
    # 返回页面
    @staticmethod
    def get(request):
        login_form = LoginForm()
        return render(request, 'users/login.html', {'login_form': login_form})

    # 处理登录表单
    @staticmethod
    def post(request):
        """处理用户的表单数据，处理流程:1.实例化表单，表单的判定
        2.用户信息的验证，利用username，从数据库中读取用户信息
        3.判断是否激活
        :param request:
        :return:
        """
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            email_mobile = request.POST.get("email_mobile", "")
            pass_word = request.POST.get("password", "")
            user = CustomBackend().authenticate(request, email_mobile=email_mobile, password=pass_word)
            mobile = authenticate(mobile=email_mobile, password=pass_word)
            if (user or mobile) is not None:
                if user.is_active:
                    login(request, user)
                    request.session["email_mobile"] = email_mobile
                    request.session["is_login"] = True
                    # temp = request.user
                    return HttpResponseRedirect(reverse("index"))  # 添加重定向的路径
                else:
                    # return JsonResponse({'status': -1, 'error': '用户未激活，请您尽快激活'})
                    return render(request, "users/login.html",
                                  {'login_form': login_form, 'error': '用户未激活，请您尽快激活'})
            else:
                # return JsonResponse({'status': -1, 'error': '用户名或密码错误'})
                return render(request, "users/login.html",
                              {'login_form': login_form, 'error': '用户名或密码错误'})
        else:
            # return JsonResponse({'status': -1, 'error': '用户名与密码格式错误'})
            error_msg = login_form.errors   # errors为错误信息
            return render(request, 'users/login.html', {"error": error_msg})
            # request["error"] = "用户名或密码错误"
            # return render(request, "users/login.html",
            #               {'login_form': login_form, 'error': '用户名与密码格式错误'})


# 用户注册的类
class RegisterView(View):
    # 返回注册页面
    @staticmethod
    def get(request):
        register_form = RegisterForm()
        return render(request, 'users/register.html', {'register_form': register_form})

    @staticmethod
    def post(request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            email = request.POST.get("email", "")
            mobile = request.POST.get("mobile", "")
            # 判断注册的用户是否已经存在
            if UserProfile.objects.filter(Q(email=email) | Q(mobile=mobile)):
                return render(request, "users/register.html", {'error': '用户已经存在了'})
            pass_word = request.POST.get("password", "")
            user_profile = UserProfile()
            user_profile.mobile = mobile
            user_profile.email = email
            user_profile.is_active = False
            # 进行密码的hash编码过程
            user_profile.password = make_password(pass_word)
            user_profile.save()
            # 发送验证邮件
            send_register_email(email, 'register')
            response_json = dict()
            response_json["flag"] = 1
            response_json["email"] = email
            response_json["mobile"] = mobile
            response_json["register_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            return render(request, 'users/login.html', response_json)
        else:
            return render(request, "users/register.html", {'error': '注册表单填写错误'})


class LogoutView(View):
    @staticmethod
    def get(request):
        logout(request)
        return HttpResponseRedirect(reverse("user_login"))


# 用户忘记密码的类
class ForgetView(View):
    @staticmethod
    def get(request):
        register_form = RegisterForm()
        return render(request, 'users/forget.html', {'register_form': register_form})

    @staticmethod
    def post(request):
        forget_form = ForgetForm(request.POST)
        if forget_form.is_valid():
            email = request.POST.get("email", "")
            mobile = request.POST.get("mobile", "")
            user_profile = UserProfile.objects.filter(Q(email=email) & Q(mobile=mobile))
            if not user_profile:
                return render(request, "users/forget.html", {'error': '用户不存在'})
            pass_word = request.POST.get("password", "")
            user_profile.update(is_active=False, password=make_password(pass_word))
            # 发送验证邮件
            send_register_email(email, 'register')
            response_json = dict()
            response_json["flag"] = 1
            response_json["email"] = email
            response_json["register_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            return render(request, 'users/login.html', response_json)
        else:
            return render(request, "users/forget.html", {'error': '注册表单填写错误'})
